using IQIGame.Onigao.Framework;
using System;
using System.Collections.Generic;

namespace IQIGame.Onigao.Game
{
    /// <summary>
    /// 可配置状态机总控管理器
    /// </summary>
    public class CFStateMachineManager : Singleton<CFStateMachineManager>
    {
        /// <summary>
        /// 所有由主控管理器自动驱动的模块管理器
        /// 如果是自驱的，则不在此队列里
        /// </summary>
        private List<CFSMModuleManager> _autoDriveMgrs = new List<CFSMModuleManager>();

        private ICFSMResLoaderCreater _loaderCreater;
        private ICFSMBlackboard _blackboard;
        private Func<int> _getSysFrameRate;

        public ICFSMBlackboard blackboard => _blackboard;

        private CFStateMachineManager()
        {

        }

        public void Init(ICFSMResLoaderCreater loaderCreater, ICFSMBlackboard blackboard, Func<int> getSysFrameRate)
        {
            this._loaderCreater = loaderCreater;
            this._blackboard = blackboard;
            this._getSysFrameRate = getSysFrameRate;
#if UNITY_EDITOR
            ManagerCenter.MonoDriver.updateEvent += OnUpdate;
            ManagerCenter.MonoDriver.onApplicationQuitEvent += OnShutdown;
#endif
        }

        private void OnUpdate(float deltaTime, float unscaledDeltaTime)
        {
            for (int i = 0; i < _autoDriveMgrs.Count; i++)
            {
                _autoDriveMgrs[i].OnUpdate(deltaTime);
            }
        }

        /// <summary>
        /// 刷新最小间隔
        /// </summary>
        /// <param name="driveBySelf">是否自己管理Update</param>
        /// <returns></returns>
        public CFSMModuleManager CreateManager(bool driveBySelf = false)
        {
            if (_loaderCreater == null || _blackboard == null)
            {
                LogGame.LogError("请先调用Init接口初始化。");
                return null;
            }
            CFSMModuleManager mgr = ClassPool.Get<CFSMModuleManager>();
            mgr.Init(_loaderCreater, driveBySelf);
            if (!driveBySelf)
            {
                _autoDriveMgrs.Add(mgr);
            }
            return mgr;
        }

        public void ReleaseManager(CFSMModuleManager mgr)
        {
            if (mgr.driveBySelf || _autoDriveMgrs.Remove(mgr))
            {
                ClassPool.Put(mgr);
            }
        }

        protected void OnShutdown()
        {
#if UNITY_EDITOR
            ManagerCenter.MonoDriver.onApplicationQuitEvent -= OnShutdown;
            ManagerCenter.MonoDriver.updateEvent -= OnUpdate;
#endif
            for (int i = 0; i < _autoDriveMgrs.Count; i++)
            {
                ClassPool.Put(_autoDriveMgrs[i]);
            }
            _autoDriveMgrs.Clear();
        }
    }
}
